
package de.fhhof.brst.dao;

import java.io.Serializable;
import java.util.List;
import org.hibernate.PersistentObjectException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.exception.GenericJDBCException;
import de.fhhof.brst.data.User;
import de.fhhof.brst.exceptions.UserAlreadyExistsException;
import de.fhhof.brst.exceptions.UserNotFoundException;
public class HibernateUserDAO implements Serializable, UserDAO {
  private Session session;

  public static final int USER_REGISTRATION_SUCCESS =  0;

  public static final int USER_ALREADY_REGISTERED =  1;

  public static final int USER_REGISTRATION_FAILURE =  2;

  public HibernateUserDAO() {

  }

  @Override
  public int registerUser(de.fhhof.brst.data.User user) throws de.fhhof.brst.exceptions.UserAlreadyExistsException {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		
		try {
			session.save(user);

			session.getTransaction().commit();
		} catch (GenericJDBCException e) {
			session.getTransaction().rollback();
			e.printStackTrace();
			throw new UserAlreadyExistsException("User already exists!");
		} finally {
			HibernateUtil.getSessionFactory().close();
		}
		return 0;
  }

  @Override
  public int deleteUser(de.fhhof.brst.data.User user) {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		session.delete(user);

		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();
		return 0;
  }

  @Override
  public de.fhhof.brst.data.User getUser(String email) throws de.fhhof.brst.exceptions.UserNotFoundException {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Query query = (Query) session
				.createQuery("from User where email = ?").setString(0, email);

		List users = query.list();
		
		if (users.size() == 0) throw new UserNotFoundException("Invalid Email-Address!"); 
		
		User user = (User) users.get(0);
		
		

		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();
		return user;
  }

  @Override
  public int editUser(de.fhhof.brst.data.User user) {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		session.update(user);

		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();
		return 0;
  }

  @Override
  public List getAllUser() {
		session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		List users = session.createQuery("from User").list();

		session.getTransaction().commit();
		HibernateUtil.getSessionFactory().close();

		return users;
  }

  public static HibernateUserDAO getHibernateUserDAO()
  {
		return new HibernateUserDAO();

  }

}
